package com.ddxz.demo.distribute.service.impl;

import com.ddxz.demo.distribute.service.LockService;
import com.ddxz.tool.web.dto.DdxzResponse;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * class description
 *
 * @author 朱宗刚
 * @version 1.0.0
 * @date 2020/11/23
 */

@Service
public class LockServiceImpl implements LockService {
    /**
     * 购买某种产品
     *
     * @param productId 产品标识
     * @return 是否购买成功
     */
    @Override
    public DdxzResponse buy(String productId) {
        RLock lock = null;
        try {
            // 该处的键值不能与redis中已有的key值相同
            lock = client.getLock(productId + "lock");
            lock.lock();
            Integer num = (Integer) template.opsForValue().get(productId);
            if(num > 0) {
                template.opsForValue().set(productId, num - 1);
            } else {
                return DdxzResponse.correct("商品售罄");
            }
            return DdxzResponse.correct("购买成功");
        } catch (Exception e){
            e.printStackTrace();
            return DdxzResponse.correct("商品售罄");
        }finally {
            assert lock != null;
            lock.unlock();
        }
    }

    private final RedisTemplate<String, Object> template;
    private final RedissonClient client;

    public LockServiceImpl(RedisTemplate<String, Object> template, RedissonClient client) {
        this.template = template;
        this.client = client;
    }
}
